package cn.smbms.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.smbms.pojo.Permission;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.RolePermission;
import cn.smbms.service.RoleService;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Controller
@RequestMapping("jsp")
public class RoleController {
	
	@Resource
	private RoleService roleService;
	
	@RequiresPermissions("order:*")
	@RequestMapping("/rolelist.do")
	public String rolelist(
			@RequestParam(name="pageIndex",required=false,defaultValue="1") Integer currentPageNo, 
			String queryname,
			String message,
			Model model){
		//分页插件(当前是第几页，每页显示的记录行数)
		Page<Object> page = PageHelper.startPage(currentPageNo, 2);
		//查询所有用户
		List<Role> roleList = roleService.getRoleListByRoleName(queryname);
		//把分页相关数据传递到freemarker
		//当前页的实际数据List<Role>
		model.addAttribute("roleList", roleList);
		//总记录数
		model.addAttribute("totalCount", page.getTotal());
		//当前是第几页
		model.addAttribute("currentPageNo", page.getPageNum());
		//一共有多少页
		model.addAttribute("totalPageCount", page.getPages());
		//传递查询参数
		model.addAttribute("queryname", queryname);
		//
		model.addAttribute("message", message);
		return "jsp/rolelist";
	}
	
	@RequestMapping("/rolemodify")
	public String rolemodify(Integer roleid, Model model){
		Role role = roleService.getRoleById(roleid);
		List<Permission> permissionList = roleService.getPermissionList();
		List<RolePermission> permissions = roleService.getRolePermissionByRoleId(roleid);
		model.addAttribute("role", role);
		model.addAttribute("permissions", permissions);
		model.addAttribute("permissionList", permissionList);
		return "jsp/rolemodify";
	}
	
	@RequestMapping("/rolemodify.do")
	public String rolemodifydo(Integer[] permission, Role role, Model model){
		//更新角色
		int i = roleService.updateRole(role);
		//更新角色权限
		int j = roleService.updateRolePermission(role.getId(), permission);
		//
		if(i>0 && j>0) {
			model.addAttribute("message", "更新成功");
		}
		return rolemodify(role.getId(), model);
	}
}
